package com.woyou.service;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.woyou.utils.DeviceUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


/**
 * 极光推送工具类
 * @author longtao.li
 *
 */
public class JPushService {
 
	private  Context mAppContext = null;
	private static final String TAG = "JPushUtils";
	private static String TOKEN = "";

	
	private static final int MSG_SET_ALIAS = 1001;
	private static final int MSG_SET_TAGS = 1002;
	private static JPushService mJPushUtils;
	public static JPushService getInstance(Context context){
		if( mJPushUtils == null ){
			mJPushUtils = new JPushService(context);
		}
		return mJPushUtils; 
	}
	
	private  JPushService(Context context){
		this.mAppContext = context;
		String pushToken = DeviceUtils.getPushToken(context);
		TOKEN  = pushToken;
		setTag();
	}
	
	public void resetToken(Context context){
		TOKEN  = DeviceUtils.getPushToken(context);
		setTag();
	}
	
	public void destory(){
		
		mAppContext.unregisterReceiver(mMessageReceiver);
	}

	  private final Handler mHandler = new Handler() {
	        @Override
	        public void handleMessage(android.os.Message msg) {
	            super.handleMessage(msg);
	            switch (msg.what) {
	            case MSG_SET_ALIAS:
	                Log.d(TAG, "Set alias in handler.");
	                JPushInterface.setAliasAndTags(mAppContext, (String) msg.obj, null, mAliasCallback);
	                break;
	                
	            case MSG_SET_TAGS:
	                Log.d(TAG, "Set tags in handler.");
	                JPushInterface.setAliasAndTags(mAppContext, null, (Set<String>) msg.obj, mTagsCallback);
	                break;
	                
	            default:
	                Log.i(TAG, "Unhandled msg - " + msg.what);
	            }
	        }
	    };
   
	    
	    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

	        @Override
	        public void gotResult(int code, String alias, Set<String> tags) {
	            String logs ;
	            switch (code) {
	            case 0:
	                logs = "Set tag and alias success";
	                Log.i(TAG, logs);
	                break;
	                
	            case 6002:
	                logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
	                Log.i(TAG, logs);
	                if (isConnected(mAppContext)) {
	                	mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
	                } else {
	                	Log.i(TAG, "No network");
	                }
	                break;
	            
	            default:
	                logs = "Failed with errorCode = " + code;
	                Log.e(TAG, logs);
	            }
	            
	            showToast(logs, mAppContext);
	        }
		    
		};
	    
	    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

	        @Override
	        public void gotResult(int code, String alias, Set<String> tags) {
	            String logs ;
	            switch (code) {
	            case 0:
	                logs = "Set tag and alias success";
	                Log.i(TAG, logs);
	                break;
	                
	            case 6002:
	                logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
	                Log.i(TAG, logs);
	                if (isConnected(mAppContext)) {
	                	mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
	                } else {
	                	Log.i(TAG, "No network");
	                }
	                break;
	            
	            default:
	                logs = "Failed with errorCode = " + code;
	                Log.e(TAG, logs);
	            }
	            
	            showToast(logs, mAppContext);
	        }
	        
	    };
	
	
	
	public  void setTag(){
		String tag = TOKEN;
		
        // 检查 tag 的有效性
		if (TextUtils.isEmpty(tag)) {
			Log.e(TAG, "tag不能为空");
			return;
		}
		
		// ","隔开的多个 转换成 Set
		String[] sArray = tag.split(",");
		Set<String> tagSet = new LinkedHashSet<String>();
		for (String sTagItme : sArray) {
			if (!isValidTagAndAlias(sTagItme)) {
				Log.e(TAG, "tag不合法");
				return;
			}
			tagSet.add(sTagItme);
		}
		
		//调用JPush API设置Tag
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));

	} 
	
	public void setAlias(){
		
		String alias =  TOKEN;
		if (TextUtils.isEmpty(alias)) {
			Log.e(TAG, "alias不能为空");
			return;
		}
		if (isValidTagAndAlias(alias)) {
			Log.e(TAG, "alias不合法");
			return;
		}
		
		//调用JPush API设置Alias
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
	}
	
	//for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.citaq.ideliver.MESSAGE_RECEIVED_ACTION";//cn.jpush.android.intent.MESSAGE_RECEIVED
	public static final String NOTIFICATION_RECEIVED_ACTION = "com.citaq.ideliver.MESSAGE_NOTIFICATION_ACTION";//cn.jpush.android.intent.MESSAGE_RECEIVED
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	
	public  void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		filter.addAction(NOTIFICATION_RECEIVED_ACTION);
		mAppContext.registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
              String messge = intent.getStringExtra(KEY_MESSAGE);
              String extras = intent.getStringExtra(KEY_EXTRAS);
              StringBuilder showMsg = new StringBuilder();
              showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
              if (!isEmpty(extras)) {
            	  showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
              }
              setCostomMsg(showMsg.toString());
			}
			if (NOTIFICATION_RECEIVED_ACTION.equals(intent.getAction())) {
				String title = intent.getStringExtra(KEY_TITLE);
				String messge = intent.getStringExtra(KEY_MESSAGE);
				
//				showCostomMsg(title, messge);
				hanldeMessage(title, messge);
			}
		}
	}
	
	private void setCostomMsg(String msg){
//		 Toast.makeText(mAppContext, msg, 1).show();
		Log.i(TAG, msg);
	}
	
	private void showCostomMsg(String title, String content){
//		View msgView = UIUtils.getPopMsgView(mUIActivity,
//				title, content, "确定",
//				new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {  
//						FloatingFunc.close(mUIActivity);
//
//					}
//				}, null, null);
//		FloatingFunc.show(mUIActivity, msgView);
	}
	/**
	 * 处理推送消息
	 * @param title
	 * @param notificationMessage
	 */
	public  void hanldeMessage(String title, String notificationMessage){
		
		if( notificationMessage.contains("U:") ){//打开网页
			String title1 = notificationMessage.substring(0, notificationMessage.indexOf("U"));
			int start = notificationMessage.indexOf(":")+1;
			String url = notificationMessage.substring(start);
			openUrl(title1, url);
			return;
		}
		
		String rule = notificationMessage.substring(0, 2);
		String message = notificationMessage.substring(2);
	        	
	        	if(rule.equals("T:")){			//显示文本
	        		
	        		showCostomMsg(title, message);
	       		
	        	}else if(rule.equals("A:")){
	        		//激活优惠券
	        		
	        	}
//	        	else if(rule.equals("U:")){		//打开网页
//	    			openUrl(message);
//	        		
//	        	}
	        	else{
	        		showCostomMsg(title, notificationMessage);
	        	}
	        	
	}

	private void openUrl(String title, String notificationMessage) {
	}
	
	 //打开网页
    private void openUrlView(final String sUrl){
//    	Intent i = new Intent(this, OpenUrlActivity.class);
//    	i.putExtra("URL", sUrl);
//    	startActivity(i);
    	
//    	Intent web = new Intent(mUIActivity, WebActivity.class);
//		web.putExtra("url", sUrl);
//		mUIActivity.startActivity(web);
    	
    }   

	
	
	
	
	
	//-------------------------------------------------------------------------------
	
	
	
	public static final String PREFS_NAME = "JPUSH_EXAMPLE";
    public static final String PREFS_DAYS = "JPUSH_EXAMPLE_DAYS";
    public static final String PREFS_START_TIME = "PREFS_START_TIME";
    public static final String PREFS_END_TIME = "PREFS_END_TIME";
    public static final String KEY_APP_KEY = "JPUSH_APPKEY";

    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }
    
    // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    // 取得AppKey
    public static String getAppKey(Context context) {
        Bundle metaData = null;
        String appKey = null;
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai)
                metaData = ai.metaData;
            if (null != metaData) {
                appKey = metaData.getString(KEY_APP_KEY);
                if ((null == appKey) || appKey.length() != 24) {
                    appKey = null;
                }
            }
        } catch (NameNotFoundException e) {

        }
        return appKey;
    }
    
    // 取得版本号
    public static String GetVersion(Context context) {
		try {
			PackageInfo manager = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return manager.versionName;
		} catch (NameNotFoundException e) { 
			return "Unknown";  
		} 
	}
	
    public static void showToast(final String toast, final Context context)
    {
    	new Thread(new Runnable() { 
			
			@Override
			public void run() {
//				Looper.prepare();
//				Toast.makeText(context, toast, Toast.LENGTH_SHORT).show(); 
//				Looper.loop(); 
			}
		}).start();
    }
    
    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }
    
	public static String getImei(Context context, String imei) {
		try {
			TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			imei = telephonyManager.getDeviceId();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
		return imei;
	}
	
	
	
	
	
	

}
